﻿using System;
using System.Windows.Threading;

namespace Rio.Framework.Pages.AppCode.Helpers
{
    public class TimeoutAction
    {
        private DispatcherTimerContainingAction timer;

        /// <summary>
        /// Initializes a new instance of the <see cref="Timeout"/> class.
        /// </summary>
        /// <param name="milliseconds">The milliseconds before perform action</param>
        public TimeoutAction(int milliseconds)
        {
            timer = new DispatcherTimerContainingAction();
            timer.Interval = new TimeSpan(0, 0, 0, 0, Convert.ToInt32(milliseconds));
        }

        /// <summary>
        /// Clears the timeout but keep the action.
        /// </summary>
        public void ClearTimeout()
        {
            if (timer != null)
            {
                timer.Stop();
                timer.Tick -= _onTimeout;
            }
        }

        /// <summary>
        /// Ends the timeout and directly perform the action.
        /// </summary>
        public void EndTimeout()
        {
            if (timer.Action != null)
                _onTimeout(timer, new EventArgs());
        }

        /// <summary>
        /// Starts the timeout with the action specified.
        /// </summary>
        /// <param name="func">The func.</param>
        public void StartTimeout(Action func)
        {
            timer.Action = func;

            timer.Tick += _onTimeout;
            timer.Start();
        }

        private void _onTimeout(object sender, EventArgs arg)
        {
            DispatcherTimerContainingAction t = sender as DispatcherTimerContainingAction;
            t.Stop();
            t.Action();
            t.Tick -= _onTimeout;
        }

        private class DispatcherTimerContainingAction : DispatcherTimer
        {
            public Action Action
            {
                get;
                set;
            }
        }
    }
}
